<template>
  <div class="view-wrapper">
    <div class="main">
      <div class="tab">
        <div class="tab_box" :class="changeIndex == index ? 'tab_box_active' : ''" @click="changeIndex = index"
          v-for="(item, index) in tabLs" :key="index">
          {{ item.name }}
        </div>
      </div>
      <!-- 基本信息 -->
      <div class="main_info" v-show="changeIndex == 0">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="店铺名称" prop="merchantId">
            <el-select v-model="ruleForm.merchantId" placeholder="请选择" filterable :disabled="shopDisabled">
              <el-option v-for="item in options" :key="item.additionalValue" :label="item.value"
                :value="item.additionalValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="团购名称：" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请填写活动名称"></el-input>
          </el-form-item>
          <el-form-item label="活动时间:" required>
            <div class="disx">
              <el-form-item prop="activityStartTime">
                <el-date-picker v-model="ruleForm.activityStartTime" type="datetime" placeholder="选择开始日期"
                  value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :clearable="false" :editable="false"
                  @blur="activeChange">
                </el-date-picker>
              </el-form-item>
              <span style="margin-right:20px">-</span>
              <el-form-item prop="activityEndTime">
                <el-date-picker v-model="ruleForm.activityEndTime" type="datetime" placeholder="选择结束日期"
                  value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="end_Date"
                  :clearable="false" :disabled="endDisabled" :editable="false">
                </el-date-picker>
              </el-form-item>
              <el-tooltip content="团购活动的开始与结束的时间，可选择最小单位为分钟" placement="top">
                <div class="el-icon-question explain_txt"></div>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item label="使用时间：" required>
            <div class="disx">
              <el-form-item prop="useStartTime">
                <el-date-picker v-model="ruleForm.useStartTime" type="date" placeholder="选择开始日期"
                  value-format="yyyy-MM-dd" format="yyyy-MM-dd" :clearable="false" :editable="false" @blur="useChange">
                </el-date-picker>
              </el-form-item>
              <span style="margin-right:20px">-</span>
              <el-form-item prop="useEndTime">
                <el-date-picker v-model="ruleForm.useEndTime" type="date" placeholder="选择结束日期" value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd" :picker-options="use_end_Date" :clearable="false" :disabled="useEndDisabled"
                  :editable="false">
                </el-date-picker>
              </el-form-item>
              <el-tooltip content="用户购买商品后可核销使用的时间，最小单位为天" placement="top">
                <div class="el-icon-question explain_txt"></div>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item label="商品库存：" key="1" prop="stock" v-if="id==undefined">
            <el-input v-model.number="ruleForm.stock" placeholder="请填写库存数量"></el-input>
          </el-form-item>
          <el-form-item label="增加库存数：" v-show="id!=undefined">
            <el-input v-model.number="ruleForm.updateStock" placeholder="请填写所需增加库存数量"></el-input>
          </el-form-item>
          <div class="stock_txt" v-if="id!=undefined">
            <span style="margin-right: 10px">当前总库存：{{info.stock}}</span>
            <span>可用库存：{{info.usable}}</span>
          </div>
          <el-form-item label="活动是否启用：" label-width="130">
            <el-switch v-model="ruleForm.enableStatus" active-value="1" inactive-value="2"></el-switch>
          </el-form-item>
          <el-form-item label="限购：" prop="limitType">
            <div class="dflex">
              <el-radio-group v-model="ruleForm.limitType" class="dflex">
                <el-radio label="1" @change="radioChange">不限</el-radio>
                <el-radio label="2">限量</el-radio>
              </el-radio-group>
              <el-input style="width: 160px !important; margin-left: 30px" v-model.number="ruleForm.limitCount"
                :disabled="ruleForm.limitType == 2 ? false : true" placeholder="请填写限购数量"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="活动价格：" prop="grouponPrice">
            <el-input v-model="ruleForm.grouponPrice" placeholder="请填写活动价格"><template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="原价：" prop="originalPrice">
            <el-input v-model="ruleForm.originalPrice" placeholder="请填写原价"><template slot="append">元</template>
            </el-input>
          </el-form-item>
          <!-- 产品详情 -->
          <div class="el_table_box">
            <div class="el_table_box_h">
              <div class="el_table_box_h_title">产品详情</div>
              <!-- <el-button type="primary" size="small" @click="addProduct">添加产品</el-button> -->
            </div>
            <div class="el_table_box_d">
              <div class="el_table_box_d_t">
                <div class="tab_index">序号</div>
                <div class="tab_name">产品名称</div>
                <div class="tab_num">产品数量</div>
                <div class="tab_operation">操作</div>
              </div>
              <div class="tab_none" v-if="ruleForm.productLs.length==0">暂无数据</div>
              <div class="el_table_box_d_b" v-for="(item,index) in ruleForm.productLs" :key="index">
                <div class="tab_index_d">{{index+1}}</div>
                <div class="tab_name_d">
                  <el-form-item label="" :prop="
                    'productLs.' + index + '.productName'
                  " :rules="rules.productName">
                    <el-input v-model="item.productName" placeholder="请输入产品名称"></el-input>
                  </el-form-item>
                  <!-- <el-input style="width:100%" placeholder="请输入产品名称"></el-input> -->
                </div>
                <div class="tab_num_d">
                  <el-form-item label="" :prop="
                    'productLs.' + index + '.productNum'
                  " :rules="rules.productNum">
                    <el-input v-model="item.productNum" placeholder="请输入产品数量 (例:1份)"></el-input>
                  </el-form-item>
                  <!-- <el-input style="width:100%" placeholder="请输入产品数量 (例:1份)"></el-input> -->
                </div>
                <div class="tab_operation_d">
                  <el-button @click="addProduct" type="primary" size="mini" v-if="index == 0">添加产品</el-button>
                  <el-button @click="deleteProduct(index)" type="danger" size="mini" v-if="index != 0">删除</el-button>
                  <!-- <span class="detail_button">删除</span> -->
                </div>
              </div>
            </div>
          </div>
          <el-form-item label="使用方式：">
            <span>到店核销</span>
          </el-form-item>
          <el-form-item label="使用规则：">
            <el-input type="textarea" :rows="6" v-model="ruleForm.useRule" show-word-limit maxlength="600"
              placeholder="请输入使用说明"></el-input>
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >立即创建</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item> -->
        </el-form>
      </div>
      <!-- 商品相册 -->
      <div class="commodity_album" v-show="changeIndex == 1">
        <div class="carousel_box_title">最多上传5张图片 (建议上传尺寸 325px*175px)</div>
        <el-upload-list :count="5" @getImgLs="getImgLs" :imgList="info.projectList" />
        <div class="carousel_box" v-if="ruleForm.projectList.length != 0">
          <div class="carousel_box_title">预览效果图</div>
          <el-carousel trigger="click" height="222px" :autoplay="true">
            <el-carousel-item v-for="(item, index) in ruleForm.projectList" :key="index">
              <el-image class="swiper_img" :src="item" fit="cover"></el-image>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <!-- 图文详情 -->
      <div class="commodity_album" v-show="changeIndex == 2">
        <div class="carousel_box_title">最多上传10张图片</div>
        <el-upload-list :count="10" @getImgLs="getimgTxtls" :imgList="info.detailList" />
        <div class="carousel_box" v-if="ruleForm.detailList.length != 0">
          <div class="carousel_box_title">预览效果图</div>
          <div class="phone_box">
            <el-image v-for="(item, indexs) in ruleForm.detailList" :key="indexs" class="swiper_img"
              :src="item" fit="cover"></el-image>
          </div>
        </div>
      </div>
      <div class="button_box">
        <el-button type="primary" :loading="loading" @click="submitForm('ruleForm')" v-if="id==undefined">立即创建
        </el-button>
        <el-button type="primary" :loading="loading" @click="submitForm('ruleForm')" v-if="id!=undefined">保存提交
        </el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </div>
    </div>
  </div>
</template>
<script>
  import {
    addGroupon,
    getInfo,
    editGroupon,
    grouponMerchant
  } from "@/api/operateActive";
  import elUploadList from "./components/el-upload-list";
  export default {
    name: "addActive",
    components: {
      elUploadList,
    },
    data() {
      return {
        shopDisabled: false,
        loading: false,
        dialogVisible: false,
        tabLs: [{
            id: 0,
            name: "基本信息"
          },
          {
            id: 1,
            name: "商品相册"
          },
          {
            id: 2,
            name: "图文详情"
          },
        ],
        options: [],
        changeIndex: 0,
        tableData: [], //产品数组
        productLs: [], //产品详情
        ruleForm: {
          merchantId: '', //店铺名称
          name: '', //团购名称
          activityStartTime: '', //活动开始时间
          activityEndTime: '', //活动结束时间
          useStartTime: '', //使用开始时间
          useEndTime: '', //使用结束时间
          stock: '', //库存数量
          updateStock: '', //增加库存量
          limitType: '1', //限购类型（1 不限 2 限制）
          limitCount: '', //限购数量
          enableStatus: '1', //是否启用（1 启用  2 停用）
          grouponPrice: '', //团购价格
          originalPrice: '', //原价
          useType: '1', //使用方式 1 到店核销
          productDetail: [], //产品详情(字符串)
          productLs: [ //产品详情数组
            {
              productName: "",
              productNum: "",
            }
          ],
          useRule: '', //使用规则
          projectList: [], //商品相册  String 类型数组 (值为url)
          detailList: [], //图文详情  String 类型数组 (值为url)
        },
        rules: { //校验规则
          merchantId: [{
            required: true,
            message: '请选择店铺',
            trigger: 'change'
          }],
          name: [{
            required: true,
            message: "请输入团购名称",
            trigger: "blur"
          }],
          activityStartTime: [{
            required: true,
            message: '请选择开始时间',
            trigger: 'change'
          }],
          activityEndTime: [{
            required: true,
            message: '请选择结束时间',
            trigger: 'change'
          }],
          useStartTime: [{
            required: true,
            message: '请选择使用开始时间',
            trigger: 'change'
          }],
          useEndTime: [{
            required: true,
            message: '请选择使用结束时间',
            trigger: 'change'
          }],
          stock: [{
            required: true,
            message: "请输入商品库存",
            trigger: "blur"
          }, {
            type: 'number',
            message: '必须为数字值',
            trigger: "blur"
          }],
          limitType: [{
            required: true,
            message: "请选择活动资源",
            trigger: "change"
          }, ],
          grouponPrice: [{
            required: true,
            message: "请填写活动价格",
            trigger: "blur"
          }],
          originalPrice: [{
            required: true,
            message: "请填写原价",
            trigger: "blur"
          }, ],
          productName: [{
            required: true,
            message: "请输入产品名称",
            trigger: "blur"
          }],
          productNum: [{
            required: true,
            message: "请输入产品数量",
            trigger: "blur"
          }],
        },
        commodityImg: [], //商品相册
        imgTxtls: [], //图文详情
        id: '', //获取详情id
        info: {}, //获取详情
        endDisabled: true,
        useEndDisabled: true,
        end_Date: this.endDate(),
        use_end_Date: this.useEndDate()
      };
    },
    computed: {},
    created() {},
    mounted() {
      let query = this.$route.query;
      this.id = query.id
      console.log(this.id)
      this.getselectList()
      if (this.id != undefined) {
        this.getInfo()
      }
    },
    methods: {
      getselectList() {
        //获取商家列表
        this.loading = true;
        grouponMerchant()
          .then((res) => {
            this.options = res.result;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      activeChange(e) {
        if (this.ruleForm.activityStartTime != null) {
          this.endDisabled = false
          this.ruleForm.activityEndTime = ''
        } else {
          this.endDisabled = true
          this.ruleForm.activityEndTime = ''
        }
      },
      useChange(e) {
        if (this.ruleForm.useStartTime != null) {
          this.useEndDisabled = false
          this.ruleForm.useEndTime = ''
        } else {
          this.useEndDisabled = true
          this.ruleForm.useEndTime = ''
        }
      },
      endDate() { //控制活动日期选择disable
        let that = this
        return {
          disabledDate(time) {
            if (that.ruleForm.activityStartTime != '' && (new Date(that.ruleForm.activityStartTime) < Date.now())) {
              // return time.getTime() <= new Date(that.ruleForm.activityStartTime).getTime()
              return time.getTime() <= new Date() - 8.64e7;
            } else if (that.ruleForm.activityStartTime != '' && (new Date(that.ruleForm.activityStartTime) > Date
                .now())) {
              return time.getTime() <= new Date(that.ruleForm.activityStartTime).getTime() - 8.64e7;
            }
          }
        }
      },
      useEndDate() { //控制使用日期选择disable
        let that = this
        return {
          disabledDate(time) {
            // if (that.ruleForm.useStartTime != '' && (new Date(that.ruleForm.useStartTime) < Date.now())) {
            //   return time.getTime() < Date.now() - 8.64e6
            // } else if (that.ruleForm.useStartTime != '' && (new Date(that.ruleForm.useStartTime) > Date
            //     .now())) {
            //   return time.getTime() <= new Date(that.ruleForm.useStartTime).getTime()
            // }
            ////使用的结束时间不能小于活动的结束时间
            if (that.ruleForm.useStartTime != '' && (new Date(that.ruleForm.useStartTime) < Date.now())) {
              console.log('小于当前时间')
              return time.getTime() <= new Date(that.ruleForm.activityEndTime).getTime() - 8.64e7;
            } else {
              console.log('大于当前时间')
              return time.getTime() <= new Date(that.ruleForm.useStartTime).getTime() - 8.64e7;
            }
            // else if (that.ruleForm.useStartTime != '' && (new Date(that.ruleForm.useStartTime) > new Date(that
            //     .ruleForm.activityEndTime))) {
            //       console.log('大于当前时间')
            //   return time.getTime() <= new Date(that.ruleForm.useStartTime).getTime() - 8.64e7;
            // }
          }
        }
      },
      radioChange(e) { //单选选择
        console.log(e)
        this.ruleForm.limitCount = ''
      },
      getInfo() { //获取商家团购信息详情
        const params = {
          id: this.id
        };
        getInfo(params).then((res) => {
          let info = res.result
          this.info = info
          this.ruleForm.merchantId = info.merchantId
          this.ruleForm.name = info.name
          this.ruleForm.activityStartTime = info.activityStartTime
          this.ruleForm.activityEndTime = info.activityEndTime
          this.ruleForm.useStartTime = info.useStartTime
          this.ruleForm.useEndTime = info.useEndTime
          // this.ruleForm.stock = info.stock
          this.ruleForm.limitType = info.limitType
          this.ruleForm.limitCount = info.limitCount
          this.ruleForm.enableStatus = info.enableStatus
          this.ruleForm.grouponPrice = info.grouponPrice
          this.ruleForm.originalPrice = info.originalPrice
          this.ruleForm.useType = info.useType
          this.ruleForm.productDetail = info.productDetail
          this.ruleForm.productLs = JSON.parse(info.productDetail)
          this.ruleForm.useRule = info.useRule
          this.ruleForm.projectList = info.projectList
          this.ruleForm.detailList = info.detailList
          this.endDisabled = false
          this.useEndDisabled = false
          this.shopDisabled = true
        });
      },
      submitForm(formName) {
        //确定
        // this.ruleForm.activityStartTime = this.ruleForm.activeTime[0]
        // this.ruleForm.activityEndTime = this.ruleForm.activeTime[1]
        // this.ruleForm.useStartTime = this.ruleForm.useTime[0]
        // this.ruleForm.useEndTime = this.ruleForm.useTime[1]
        this.ruleForm.productDetail = JSON.stringify(this.ruleForm.productLs)
        console.log('this.ruleForm', this.ruleForm);
        // return
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            if (this.ruleForm.projectList.length == 0) {
              this.$message({
                message: "商品相册不能为空",
                type: "warning",
              });
              return
            }
            if (this.ruleForm.limitType == 2 && this.ruleForm.limitCount == '') {
              this.$message({
                message: "请填写限购数量",
                type: "error",
              });
              return
            }
            var pat = /^\+?[1-9][0-9]*$/;
            if (this.ruleForm.updateStock != '' && !pat.test(this.ruleForm.updateStock)) {
              this.$message({
                message: "请填写正确的增加库存数量",
                type: "error",
              });
              return
            }

            this.loading = true
            if (this.id == undefined) { //新增
              var params = {
                ...this.ruleForm,
              };
              addGroupon(params).then((res) => {
                  this.$message({
                    message: "恭喜！提交成功，等待平台审核",
                    type: "success",
                  });
                  setTimeout(() => {
                    this.$router.push({
                      path: "./dy-buying",
                    });
                    this.loading = false
                  }, 1000);
                })
                .finally(() => {
                  this.loading = false;
                });
            } else { //编辑
              var params = {
                ...this.ruleForm,
                id: this.id
              };
              editGroupon(params).then((res) => {
                  this.$message({
                    message: "修改成功",
                    type: "success",
                  });
                  setTimeout(() => {
                    this.$router.push({
                      path: "./dy-buying",
                    });
                    this.loading = false
                  }, 1000);
                })
                .finally(() => {
                  this.loading = false;
                });
            }

          } else {
            this.$message.error("请填写基本信息");
            console.log("error submit!!");
            return false;
          }
        });
      },
      resetForm(formName) {
        //重置
        this.$refs[formName].resetFields();
      },
      addProduct() {
        //添加产品
        this.ruleForm.productLs.push({
          productName: "", //产品名称
          productNum: "", //产品数量
        });
      },
      deleteProduct(index) {
        //删除产品
        this.ruleForm.productLs.splice(index, 1);
      },
      getImgLs(e) {
        //商品相册
        // this.commodityImg = e;
        this.ruleForm.projectList = e
      },
      getimgTxtls(e) {
        //图文详情
        // this.imgTxtls = e;
        this.ruleForm.detailList = e
      },
    },
  };

</script>
<style lang="scss" scoped>
  ::v-deep.el-input--medium .el-input__inner {
    width: 350px !important;
  }

  ::v-deep.el-input-group {
    width: 350px !important;
  }

  ::v-deep.disx .el-input--medium .el-input__inner {
    width: 200px !important;
  }

  ::v-deep.dflex .el-input--medium .el-input__inner {
    width: 185px !important;
  }

  ::v-deep.el-textarea__inner {
    width: 350px !important;
    height: 200px !important;
  }

  ::v-deep.el_table_box_d_b .el-input--medium .el-input__inner {
    width: 100% !important;
  }

  ::v-deep.el_table_box_d_b .el-form-item {
    margin-bottom: 0 !important;
    width: 100% !important;
  }

  ::v-deep.el_table_box_d_b .el-form-item--medium .el-form-item__content {
    margin-left: 0 !important;
  }

  .main {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px;
  }

  .tab {
    display: flex;
    align-items: center;
    height: 40px;
  }

  .tab_box {
    font-size: 14px;
    height: 100%;
    width: 100px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    border: 1px solid #dfe6ec;
    border-radius: 4px 0 0 4px;
    color: #333;
  }

  .tab_box:hover {
    opacity: 0.8;
  }

  .tab_box_active {
    background-color: #ff9300;
    border: 1px solid #ff9300;
    color: #fff;
  }

  .tab_box:nth-child(2) {
    border-right: 0;
    border-left: 0;
    border-radius: 0;
  }

  .tab_box:nth-child(3) {
    border-radius: 0 4px 4px 0;
  }

  .main_info {
    margin-top: 40px;
  }

  .stock_txt {
    font-size: 13px;
    color: #333333;
    padding-left: 100px;
    margin-bottom: 20px;
  }

  .dflex {
    display: flex;
    align-items: center;
  }

  .el_table_box {
    padding: 0 20px 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-left: 100px;
    margin-bottom: 20px;
  }

  .el_table_box_h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f3f3;
    margin-bottom: 14px;
  }

  .el_table_box_h_title {
    border-left: 4px solid #ff9300;
    padding-left: 4px;
  }

  .commodity_album {
    padding-top: 20px;
  }

  .carousel_box {
    padding-top: 60px;
    width: 400px;
  }

  .carousel_box_title {
    font-size: 15px;
    // color: #333333;
    color: #ff9300;
    margin-bottom: 20px;
  }

  .swiper_img {
    width: 100%;
    height: 100%;
  }

  .phone_box {
    border: 10px solid #f3f3f3;
    border-radius: 8px;
    line-height: 0;
  }

  .button_box {
    padding-top: 30px;
    padding-left: 100px;
  }

  .explain_txt {
    font-size: 20px;
    margin-left: 20px;
    color: #ff9300;
  }

  .el_table_box_d {
    border: 1px solid #dfe6ec;
    width: 100%;
  }

  .el_table_box_d_t {
    display: flex;
    align-items: center;
    color: #909399;
    font-size: 15px;
    font-weight: bold;
  }

  .tab_index {
    width: 64px;
    padding: 10px;
    border-right: 1px solid #dfe6ec;
    height: 56px;
    display: flex;
    align-items: center;
  }

  .tab_name {
    height: 56px;
    display: flex;
    align-items: center;
    flex: 1;
    padding: 10px;
    border-right: 1px solid #dfe6ec;
  }

  .tab_num {
    height: 56px;
    display: flex;
    align-items: center;
    width: 35%;
    padding: 10px;
    border-right: 1px solid #dfe6ec;
  }

  .tab_operation {
    width: 160px;
    padding: 10px;
    height: 56px;
    display: flex;
    align-items: center;
  }

  .tab_index_d {
    width: 64px;
    padding: 10px;
    border-right: 1px solid #dfe6ec;
    height: 76px;
    display: flex;
    align-items: center;
  }

  .tab_name_d {
    height: 76px;
    display: flex;
    align-items: center;
    flex: 1;
    padding: 10px;
    border-right: 1px solid #dfe6ec;
  }

  .tab_num_d {
    height: 76px;
    display: flex;
    align-items: center;
    width: 35%;
    padding: 10px;
    border-right: 1px solid #dfe6ec;
  }

  .tab_operation_d {
    width: 160px;
    padding: 10px;
    height: 76px;
    display: flex;
    align-items: center;
  }

  .el_table_box_d_b {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 15px;
    border-top: 1px solid #dfe6ec;
  }

  .detail_button {
    color: #ff4949;
    font-size: 14px;
    cursor: pointer;
  }

  .tab_none {
    color: #909399;
    font-size: 15px;
    border-top: 1px solid #dfe6ec;
    width: 100%;
    text-align: center;
    padding: 20px 0;
  }

  .disx {
    display: flex;
    align-items: center;
  }

</style>
